import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Sparkles, ArrowRight, ArrowLeft, Check, X } from 'lucide-react';

interface AISubAgentGeneratorProps {
  onGenerate: (config: any) => void;
  onCancel: () => void;
}

const AVAILABLE_TOOLS = [
  'Read', 'Write', 'Bash', 'Grep', 'Glob', 'List', 'Search'
];

const AVAILABLE_MODELS = [
  { value: 'sonnet', label: 'Claude Sonnet (Balanced)' },
  { value: 'opus', label: 'Claude Opus (Most Capable)' },
  { value: 'haiku', label: 'Claude Haiku (Fastest)' },
  { value: 'inherit', label: 'Inherit from Parent' },
];

const CATEGORIES = [
  'development', 'testing', 'security', 'documentation', 
  'database', 'devops', 'design', 'analysis'
];

export function AISubAgentGenerator({ onGenerate, onCancel }: AISubAgentGeneratorProps) {
  const [step, setStep] = useState<'describe' | 'review'>('describe');
  const [description, setDescription] = useState('');
  const [generating, setGenerating] = useState(false);
  const [generatedConfig, setGeneratedConfig] = useState<any>(null);

  const handleGenerate = async () => {
    if (!description.trim()) {
      return;
    }

    setGenerating(true);

    try {
      // Simulate AI generation (in real implementation, this would call an API)
      await new Promise(resolve => setTimeout(resolve, 2000));

      // Generate a sub-agent configuration based on the description
      const config = generateConfigFromDescription(description);
      setGeneratedConfig(config);
      setStep('review');
    } catch (error) {
      console.error('Failed to generate sub-agent:', error);
    } finally {
      setGenerating(false);
    }
  };

  const handleAccept = () => {
    if (generatedConfig) {
      onGenerate(generatedConfig);
    }
  };

  const handleRegenerate = () => {
    setStep('describe');
    setGeneratedConfig(null);
  };

  const updateConfig = (field: string, value: any) => {
    setGeneratedConfig({
      ...generatedConfig,
      [field]: value,
    });
  };

  const toggleTool = (tool: string) => {
    const tools = generatedConfig.tools || [];
    const updated = tools.includes(tool)
      ? tools.filter((t: string) => t !== tool)
      : [...tools, tool];
    updateConfig('tools', updated);
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold flex items-center gap-2">
            <Sparkles className="w-5 h-5 text-purple-500" />
            AI Sub-Agent Generator
          </h2>
          <p className="text-sm text-muted-foreground mt-1">
            {step === 'describe' 
              ? 'Describe what you want the sub-agent to do'
              : 'Review and customize the generated configuration'}
          </p>
        </div>
        <Button variant="ghost" onClick={onCancel}>
          <X className="w-4 h-4 mr-2" />
          Cancel
        </Button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6">
        {step === 'describe' ? (
          <Card>
            <CardHeader>
              <CardTitle>Describe Your Sub-Agent</CardTitle>
              <CardDescription>
                Tell us what you want this sub-agent to do. Be as specific as possible.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Example: I need a sub-agent that reviews TypeScript code for type safety issues, checks for proper error handling, and suggests improvements for code readability..."
                  rows={8}
                  className="mt-2"
                />
                <p className="text-xs text-muted-foreground mt-2">
                  {description.length} characters
                </p>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-md p-4">
                <h4 className="font-semibold text-sm mb-2">💡 Tips for better results:</h4>
                <ul className="text-sm space-y-1 text-muted-foreground">
                  <li>• Be specific about the sub-agent's purpose</li>
                  <li>• Mention the types of tasks it should handle</li>
                  <li>• Include any specific tools or capabilities needed</li>
                  <li>• Describe the expected output or behavior</li>
                </ul>
              </div>

              <Button 
                onClick={handleGenerate} 
                disabled={!description.trim() || generating}
                className="w-full"
                size="lg"
              >
                {generating ? (
                  <>
                    <Sparkles className="w-4 h-4 mr-2 animate-spin" />
                    Generating...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4 mr-2" />
                    Generate Sub-Agent
                  </>
                )}
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-6">
            {/* Generated Configuration */}
            <Card>
              <CardHeader>
                <CardTitle>Generated Configuration</CardTitle>
                <CardDescription>
                  Review and customize the AI-generated sub-agent configuration
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="name">Name</Label>
                  <Input
                    id="name"
                    value={generatedConfig?.name || ''}
                    onChange={(e) => updateConfig('name', e.target.value)}
                  />
                </div>

                <div>
                  <Label htmlFor="gen-description">Description</Label>
                  <Textarea
                    id="gen-description"
                    value={generatedConfig?.description || ''}
                    onChange={(e) => updateConfig('description', e.target.value)}
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="prompt">System Prompt</Label>
                  <Textarea
                    id="prompt"
                    value={generatedConfig?.prompt || ''}
                    onChange={(e) => updateConfig('prompt', e.target.value)}
                    rows={6}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    {generatedConfig?.prompt?.length || 0} characters
                  </p>
                </div>

                <div>
                  <Label>Category</Label>
                  <div className="flex flex-wrap gap-2 mt-2">
                    {CATEGORIES.map((cat) => (
                      <Badge
                        key={cat}
                        variant={generatedConfig?.category === cat ? 'default' : 'outline'}
                        className="cursor-pointer"
                        onClick={() => updateConfig('category', cat)}
                      >
                        {cat}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div>
                  <Label>Model</Label>
                  <div className="grid grid-cols-2 gap-2 mt-2">
                    {AVAILABLE_MODELS.map((model) => (
                      <Button
                        key={model.value}
                        variant={generatedConfig?.model === model.value ? 'default' : 'outline'}
                        onClick={() => updateConfig('model', model.value)}
                        className="justify-start"
                      >
                        {model.label}
                      </Button>
                    ))}
                  </div>
                </div>

                <div>
                  <Label>Tools</Label>
                  <div className="flex flex-wrap gap-2 mt-2">
                    {AVAILABLE_TOOLS.map((tool) => (
                      <Badge
                        key={tool}
                        variant={(generatedConfig?.tools || []).includes(tool) ? 'default' : 'outline'}
                        className="cursor-pointer"
                        onClick={() => toggleTool(tool)}
                      >
                        {tool}
                      </Badge>
                    ))}
                  </div>
                  <p className="text-xs text-muted-foreground mt-2">
                    {generatedConfig?.tools?.length || 0} tools selected
                  </p>
                </div>
              </CardContent>
            </Card>

            {/* Actions */}
            <div className="flex gap-2">
              <Button variant="outline" onClick={handleRegenerate} className="flex-1">
                <ArrowLeft className="w-4 h-4 mr-2" />
                Back to Description
              </Button>
              <Button onClick={handleAccept} className="flex-1">
                <Check className="w-4 h-4 mr-2" />
                Accept & Create
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Helper function to generate config from description
function generateConfigFromDescription(description: string): any {
  // This is a simplified version. In a real implementation, this would use AI
  const lowerDesc = description.toLowerCase();
  
  // Determine category based on keywords
  let category = 'development';
  if (lowerDesc.includes('test')) category = 'testing';
  else if (lowerDesc.includes('security') || lowerDesc.includes('audit')) category = 'security';
  else if (lowerDesc.includes('document') || lowerDesc.includes('doc')) category = 'documentation';
  else if (lowerDesc.includes('database') || lowerDesc.includes('sql')) category = 'database';
  else if (lowerDesc.includes('deploy') || lowerDesc.includes('ci/cd')) category = 'devops';
  else if (lowerDesc.includes('ui') || lowerDesc.includes('design')) category = 'design';
  else if (lowerDesc.includes('analyze') || lowerDesc.includes('performance')) category = 'analysis';

  // Determine tools based on keywords
  const tools: string[] = [];
  if (lowerDesc.includes('read') || lowerDesc.includes('file') || lowerDesc.includes('code')) tools.push('Read');
  if (lowerDesc.includes('write') || lowerDesc.includes('create') || lowerDesc.includes('modify')) tools.push('Write');
  if (lowerDesc.includes('search') || lowerDesc.includes('find')) tools.push('Grep', 'Glob');
  if (lowerDesc.includes('execute') || lowerDesc.includes('run') || lowerDesc.includes('command')) tools.push('Bash');

  // Determine model based on complexity
  let model = 'sonnet';
  if (lowerDesc.includes('complex') || lowerDesc.includes('advanced') || lowerDesc.includes('security')) {
    model = 'opus';
  } else if (lowerDesc.includes('simple') || lowerDesc.includes('quick') || lowerDesc.includes('fast')) {
    model = 'haiku';
  }

  // Generate name from description
  const name = description.split('.')[0].trim().slice(0, 50) + ' Agent';

  // Generate system prompt
  const prompt = `You are a specialized AI assistant focused on: ${description}

Your responsibilities include:
- Understanding and analyzing the specific requirements
- Providing detailed and accurate responses
- Following best practices in your domain
- Being helpful, thorough, and precise

Always strive for excellence in your responses.`;

  return {
    id: `ai-generated-${Date.now()}`,
    name,
    description: description.slice(0, 200),
    prompt,
    tools: tools.length > 0 ? tools : ['Read', 'Write'],
    model,
    category,
    tags: ['ai-generated'],
  };
}

